package com.lanhao.aot.future;

import java.util.concurrent.TimeUnit;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;

@RestController
@RequestMapping("/future")
public class FutureCallbackConstroller {
	
	@GetMapping("/getValue/{traceId}")
	public ResponseEntity<?> getValue(@PathVariable String traceId) {
		String futureResult = StringUtils.EMPTY;
		try {
			SyncFuture<String> syncFuture = new SyncFuture<String>();
			Const.futureCache.put(traceId, syncFuture);
			futureResult = syncFuture.get(Const.SYNC_WAIT_TIME, TimeUnit.SECONDS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>(futureResult, HttpStatus.OK);
	}
	
	@GetMapping("/setValue/{traceId}")
	public ResponseEntity<?> setValue(@PathVariable String traceId) {
		try {
			SyncFuture<String> syncFuture = Const.futureCache.getIfPresent(traceId);
			if (syncFuture != null) {
				syncFuture.setResponse("获取成功了");
				Const.futureCache.invalidate(traceId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>("success", HttpStatus.OK);
	}
}
